package com.haixiaoke.saas.enterprise.role.controller;

import com.haixiaoke.saas.common.annotation.Log;
import com.haixiaoke.saas.common.annotation.TenantScope;
import com.haixiaoke.saas.common.constant.UserConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.core.domain.entity.SysMenu;
import com.haixiaoke.saas.common.core.page.TableDataInfo;
import com.haixiaoke.saas.common.enums.BusinessType;
import com.haixiaoke.saas.common.tenant.TenantContext;
import com.haixiaoke.saas.common.utils.StringUtils;
import com.haixiaoke.saas.common.utils.poi.ExcelUtil;
import com.haixiaoke.saas.role.domain.BizRole;
import com.haixiaoke.saas.role.service.IBizRoleMenuService;
import com.haixiaoke.saas.role.service.IBizRoleService;
import com.haixiaoke.saas.system.BaseController;
import com.haixiaoke.saas.system.service.ISysMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 企业端角色信息Controller
 *
 * @author panda
 * @date 2023-12-29
 */
@RestController
@RequestMapping("/enterprise/role/role")
public class EnterpriseBizRoleController extends BaseController {
    @Autowired
    private IBizRoleService bizRoleService;
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private IBizRoleMenuService iBizRoleMenuService;

    /**
     * 查询企业端角色信息列表
     */
    @PreAuthorize("@ss.hasPermi('enterprise:role:list')")
    @GetMapping("/list")
    @TenantScope
    public TableDataInfo list(BizRole bizRole) {
        startPage();
        bizRole.setTenantId(TenantContext.getTenantId());
        List<BizRole> list = bizRoleService.selectRolePage(bizRole);
        return getDataTable(list);
    }

    /**
     * @param bizRole
     * @return
     */
    @GetMapping("/listByEnterprise")
    @TenantScope
    public AjaxResult listByEnterprise(BizRole bizRole) {
        bizRole.setTenantId(TenantContext.getTenantId());
        List<BizRole> list = bizRoleService.selectRoleList(bizRole);
        return success(list);
    }

    /**
     * 导出企业端角色信息列表
     */
    @PreAuthorize("@ss.hasPermi('enterprise:role:export')")
    @Log(title = "企业端角色信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizRole bizRole) {
        List<BizRole> list = bizRoleService.selectBizRoleList(bizRole);
        ExcelUtil<BizRole> util = new ExcelUtil<BizRole>(BizRole.class);
        util.exportExcel(response, list, "企业端角色信息数据");
    }

    /**
     * 获取企业端角色信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('enterprise:role:query')")
    @GetMapping(value = "/{roleId}")
    public AjaxResult getInfo(@PathVariable("roleId") Long roleId) {
        return success(bizRoleService.selectBizRoleByRoleId(roleId));
    }

    /**
     * 新增企业端角色信息
     */
    @PreAuthorize("@ss.hasPermi('enterprise:role:add')")
    @Log(title = "企业端角色信息", businessType = BusinessType.INSERT)
    @PostMapping
    @TenantScope
    public AjaxResult add(@RequestBody BizRole bizRole) {
        bizRole.setTenantId(TenantContext.getTenantId());
        if (!bizRoleService.checkManageRoleName(bizRole)) {
            return error("新增角色'" + bizRole.getRoleName() + "'失败，角色名称已存在");
        }else if (!bizRoleService.checkRoleKeyUnique(bizRole)) {
            return error("新增角色'" + bizRole.getRoleName() + "'失败，角色权限已存在");
        }
        bizRole.setCreateBy(getUsername());
        return toAjax(bizRoleService.insertRole(bizRole));
    }

    /**
     * 修改企业端角色信息
     */
    @PreAuthorize("@ss.hasPermi('enterprise:role:edit')")
    @Log(title = "企业端角色信息", businessType = BusinessType.UPDATE)
    @PutMapping
    @TenantScope
    public AjaxResult edit(@RequestBody BizRole bizRole) {
        bizRole.setTenantId(TenantContext.getTenantId());
        if (!bizRoleService.checkManageRoleName(bizRole)) {
            return error("修改角色'" + bizRole.getRoleName() + "'失败，角色名称已存在");
        }else if (!bizRoleService.checkRoleKeyUnique(bizRole)) {
            return error("新增角色'" + bizRole.getRoleName() + "'失败，角色权限已存在");
        }
        bizRole.setUpdateBy(getUsername());
        return toAjax(bizRoleService.updateBizRole(bizRole));
    }

    /**
     * 删除企业端角色信息
     */
    @PreAuthorize("@ss.hasPermi('enterprise:role:remove')")
    @Log(title = "企业端角色信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{roleId}")
    public AjaxResult remove(@PathVariable("roleId") Long roleId) {
        if (bizRoleService.checkRoleExistUser(roleId)) {
            return warn("角色已关联用户，请解除后再删除");
        }
        return toAjax(bizRoleService.deleteBizRoleByRoleId(roleId));
    }

    /**
     * 查询该角色的菜单权限与所有菜单--树状结构
     */
    @GetMapping("/roleMenuTreeselect/{roleId}")
    @TenantScope
    public AjaxResult roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        if (roleId == null) {
            return error("角色数据异常");
        }
        BizRole roleByRoleId = bizRoleService.selectBizRoleByRoleId(roleId);
        if (!TenantContext.getTenantId().equals(roleByRoleId.getTenantId())) {
            return error("该角色不属于当前机构");
        }
        List<SysMenu> sysMenus = bizRoleService.selectMenuList(roleId, UserConstants.SERVER_OWNER_ENTERPRISE);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("menuIdsByRole", iBizRoleMenuService.selectMenuIdsByRoleId(roleId));
        ajax.put("menus", menuService.buildMenuTreeSelect(sysMenus));
        return ajax;
    }

    /**
     * 设置角色权限菜单
     */
    @PreAuthorize("@ss.hasPermi('enterprise:role:edit')")
    @PutMapping("/editMenuByRole")
    @TenantScope
    public AjaxResult editMenuByRole(@RequestBody BizRole role) {
        BizRole roleByRoleId = bizRoleService.selectBizRoleByRoleId(role.getRoleId());
        if (!TenantContext.getTenantId().equals(roleByRoleId.getTenantId())) {
            return error("该角色不属于当前机构");
        }
        if (StringUtils.isNull(role.getRoleId()) || StringUtils.isEmpty(role.getMenuIds())) {
            return AjaxResult.error("菜单数据缺失");
        }
        return toAjax(bizRoleService.editMenuByRole(role));
    }

    /**
     * 查询该角色的数据权限范围
     */
    @PreAuthorize("@ss.hasPermi('enterprise:role:list')")
    @GetMapping("/permissionSelect/{roleId}")
    @TenantScope
    public AjaxResult permissionSelect(@PathVariable("roleId") Long roleId) {
        if (roleId == null) {
            return error("角色数据异常");
        }
        BizRole roleByRoleId = bizRoleService.selectBizRoleByRoleId(roleId);
        if (!TenantContext.getTenantId().equals(roleByRoleId.getTenantId())) {
            return error("该角色不属于当前机构");
        }
        return success(bizRoleService.selectPermissionByRoleId(roleId));
    }

    /**
     * 设置数据权限
     */
    @PreAuthorize("@ss.hasPermi('enterprise:role:edit')")
    @Log(title = "企业端角色信息", businessType = BusinessType.UPDATE)
    @PutMapping("/editPermission")
    @TenantScope
    public AjaxResult editPermission(@RequestBody BizRole bizRole) {
        BizRole roleByRoleId = bizRoleService.selectBizRoleByRoleId(bizRole.getRoleId());
        if (!TenantContext.getTenantId().equals(roleByRoleId.getTenantId())) {
            return error("该角色不属于当前机构");
        }
        return toAjax(bizRoleService.updateRolePermission(bizRole));
    }
}
